package com.xxx.ticket;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/7/30 13:47
 * @Copyright 博为峰
 */

//线程任务类

/*
  synchronized(对象){//锁
     被同步的代码（有可能出现线程安全问题的代码）
  }

  锁:
  偏向锁
  轻量锁
  重量锁 synchronized
  公平锁
  非公平锁
  悲观锁
  乐观锁

 */
public class Ticket02 implements Runnable {

    public static int num = 100;
    public static boolean flag = true;
    public Object obj = new Object();

    @Override
    public void run() {
        while (flag) {//num = 1  0 -1
            //同步代码块
//            synchronized (obj) {//t0,t1,t2,t3
            saleTicketStatic();
//            }
        }
    }

    //同步方法  当前对象(this) final Ticket02 ticket02 = new Ticket02();
    private synchronized void saleTicket() {
        if (num > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "," + num--);
        } else {
            flag = false;
        }
    }

    //字节码文件(.class)对象(Class类的对象)
    private static synchronized void saleTicketStatic() {
        if (num > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "," + num--);
        } else {
            flag = false;
        }
    }
}
